import React from 'react';

export class Parent extends React.Component {
  constructor() {
    super();
    // 兄弟组件之间传值的数据容器
    this.state = {
      msg: '',
    };
  }

  // 子组件B给父组件传递消息的函数
  sendMsg = (msg) => {
    console.log('父组件', msg);
    this.setState({
      msg: msg,
    });
  };

  render() {
    return (
      <div style={{ border: '1px solid red', padding: 20 }}>
        <h2>父组件</h2>
        <ChildA msg={this.state.msg} />
        <ChildB sendMsg={this.sendMsg} />
      </div>
    );
  }
}

class ChildA extends React.Component {
  render() {
    return (
      <div style={{ border: '1px solid blue', padding: 20 }}>
        <h2>ChildA</h2>
        <h2>我弟传来的消息: {this.props.msg}</h2>
      </div>
    );
  }
}

class ChildB extends React.Component {
  render() {
    return (
      <div style={{ border: '1px solid blue', padding: 20 }}>
        <h2>ChildB</h2>
        <button onClick={() => this.props.sendMsg('我挨打了')}>发消息</button>
      </div>
    );
  }
}
